package com.lin.controller;

import com.lin.util.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.StandardCharsets;

@RequestMapping("/demo3")
@Controller
public class Demo3 {


    /*
     *  RabbitMQ实现消息订阅机制
     *  前面我们直接将消息送如队列中去，但是RabbitMQ需要通过exchange来帮助我们，前面我们只是指定了默认的交换机""channel.basicPublish("", "hello", null, message.getBytes());
     *  exchange就决定了消息和队列之间的映射关系。
     *  比如生产者将消息发送给交换机 它可以选择将消息发送到特定的队列，或者一个主题的队列，或者直接丢弃消息。
     *  RabbitMQ中exchange的类型有direct, topic, headers , fanout
     *  fanout 就可以用来做广播，这个交换机很简单，将收到的信息 传入所有它连接的队列中去
     */
    @Value("${queue.demo3_exchange_name}")
    private String EXCHANGE_NAME;

//    localhost:8080/demo3/broadcast
    @RequestMapping("/broadcast")
    @ResponseBody
    public String broadcast() {
        try (Connection connection = RabbitUtil.getConnection();
             Channel channel = connection.createChannel();
        ) {
            channel.exchangeDeclare(EXCHANGE_NAME,"fanout");
            String message  = "林渊广播电台现在开始广播";
            channel.basicPublish(EXCHANGE_NAME,"", MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "广播成功";
    }
}
